<?php
namespace App\Library\Common;

/**
 * 公共插件
 */
class Common extends \Phalcon\Mvc\Controller
{


    /**
     * 过滤.html后缀
     * @param string $str
     */
    public static function filterHtmlFix(string $str)
    {
        $res = $str;
        if (strpos($str, '.html')) {
            $res = substr($str, 0, strrpos($str, '.'));
        }
        if (strpos($str, 'index.html') || strpos($str, 'Index.html')) {
            $res = substr($str, 0, strrpos($str, '/') + 1);
        }
        return $res;
    }

    /**
     * 时间戳转换几分钟几秒几天前
     * @param $time 数据库中要处理的时间戳
     * @return bool|string
     */
    public static function changeTime($time)
    {
        $time = (int)substr($time, 0, 10);
        $ext = time() - $time;
        $str = '';
        if ($ext < 60) {
            $str = sprintf("刚刚", $ext);
        } elseif ($ext < 3600) {
            $str = sprintf("%d分钟前", floor($ext / 60));
        } elseif ($ext < 86400) {
            $str = sprintf("%d小时前", floor($ext / 3600));
        } elseif ($ext < 2592000) {
            $str = sprintf("%d天前", floor($ext / 86400));
        } else {
            $str = date("Y-m-d H:i:s", $time);
        }
        return $str;
    }


    /*
    /**
     * 显示404
     *
     * @return boolean
     */
    public function show404()
    {
        $this->dispatcher->forward(array(
            'namespace' => 'App\Frontend\Controllers',
            'controller' => 'http',
            'action' => 'show404'
        ));
        return false;
    }

    /**
     * 保存跳转
     */
    public static function saveRedirect($url)
    {
        header('Content-type: text/html; charset=utf-8');
        echo '<script type="text/javascript">alert("保存成功！");window.location.href="' . $url . '"</script>';
    }

    /**
     * 获取IP地址
     * @return Ambigous <unknown, string>
     */
    public static function getIP()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
        }
        return $ip;
    }

    /**
     * 输出js脚本
     *
     * @param string $str
     */
    public static function script($str)
    {
        echo '<script type="text/javascript">' . $str . '</script>';
    }

    /**
     * 字符数字混合随机码
     * @param number 生成位数
     * @return string
     */
    public static function randomStr($num = 6)
    {
        $str = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $random = '';
        for ($i = 0; $i < $num; $i++) {
            $random .= $str[mt_rand(0, 60)];
        }
        return $random;
    }

    /**
     * 删除文件
     * @param string $path
     */
    public static function removeFile($path)
    {
        if (file_exists($path)) {
            unlink($path);
        }
    }

    /**
     * 读取目录下所有文件
     * @param string $dir
     * @return array 文件列表数组
     */
    public function readFiles($dir)
    {
        $files = scandir($dir);
        $files = array_diff($files, [
            '.',
            '..'
        ]);
        return $files;
    }

    /**
     * 创建目录
     * @param string $path
     */
    public static function createDir($path)
    {
        if (!empty($path)) {
            if (!file_exists($path)) {
                mkdir($path, '0777', true);
            }
        }
    }

    /**
     * 设置cookie
     * @param 键 $key
     * @param 值 $value
     * @param 时间 $time
     */
    public function cookie($key, $value = null, $time = 3600)
    {
        if ($key && $value) {
            $this->cookies->set(COOKIES_PREFIX . $key, $value, time() + $time, '/', 0, '.' . HOST);
            //解决微信浏览器下面和开发者工具下面 cookie问题,微信开发 不发送
            // if ( !strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') || (strpos($_SERVER['HTTP_USER_AGENT'],'wechatdevtools'))) {
            //     $this->cookies->send();
            // }
            $this->cookies->send();
        } elseif ($key && !$value) {
            return rtrim($this->cookies->get(COOKIES_PREFIX . $key)->getValue(), "\0");
        }
    }

    /**
     * 删除cookies
     * @param string $key
     */
    public function cookieDelete($key)
    {
        $this->cookies->set(COOKIES_PREFIX . $key, '1', time() - 3600, '/', 0, '.' . HOST)->send();
        $rememberMeCookie = $this->cookies->get(COOKIES_PREFIX . $key);
        $rememberMeCookie->delete();
        //return $this->cookies->send();
    }
    public function sessions() {
        return $this->session;
    }
    /**
     * 判断文件是否过期
     * @param string $filename
     * @param string $lifetime
     * @return boolean
     */
    public static function fileTimeExpire($filename, $lifetime)
    {
        if ($filename) {
            if (file_exists($filename)) {
                $time = filemtime($filename);
                $time = time() - $time;
                if ($time <= $lifetime) {
                    return false;
                } else {
                    return true;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * @param array $array
     * @param null $char 指定字符
     * @return array
     */
    public static function trimArray(array $array, $char = null)
    {
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $char ? trim($value, $char) : trim($value);
            }
        }
        return $array;
    }

    /**
     * 验证邮箱
     */
    public static function isEmail($email)
    {
        return preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/", $email);
    }

    /**
     * 验证手机
     */
    public static function isMobile($mobile)
    {
        return preg_match("/^1[34578][0-9]{9}$/", $mobile);
    }

    /**
     * 获取当前日期范围的周数
     */
    public static function getWeek()
    {
        $week = date('w') == 0 ? 7 : date('w');
        $day = date('d');
        $startDay = $day - $week + 1;
        $stopDay = 7 - $week + $day;
        $date['startDateStr'] = mktime(0, 0, 0, date('m'), $startDay, date('y'));
        $date['stopDateStr'] = mktime(0, 0, 0, date('m'), $stopDay, date('y'));
        $date['startDate'] = date('Y-m-d', mktime(0, 0, 0, date('m'), $startDay, date('y')));
        $date['stopDate'] = date('Y-m-d', mktime(0, 0, 0, date('m'), $stopDay, date('y')));
        return $date;
    }

    public static function getMonth()
    {
        $date['startMonthStr'] = mktime(0, 0, 0, date("m"), 1, date("Y"));
        $date['stopMonthStr'] = mktime(0, 0, 0, date("m"), date("t"), date("Y"));
        $date['startMonth'] = date('Y-m-d', mktime(0, 0, 0, date("m"), 1, date("Y")));
        $date['stopMonth'] = date('Y-m-d', mktime(0, 0, 0, date("m"), date("t"), date("Y")));
        return $date;
    }

    /**
     * 获取缓存配置文件
     */
    public function getCacheConfigFile($fileName)
    {
        $path = 'data/caches/config/';
        $fileName = $path . $fileName . '.config.php';
        // 如果配置文件存在
        if (file_exists($fileName)) {
            return file_get_contents($fileName);
        }
        return false;
    }

    /**
     * CURL
     * @param string $url
     */
    public static function curl($url, array $data = null)
    {
        //1.初始化curl
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($data) {
            //使用post提交数据
            curl_setopt($ch, CURLOPT_POST, 1);
            //设置 post提交的数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //关闭直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        return $output;
    }

    /**
     * 设置缓存文件
     */
    public function setCacheFile($fileName, $data)
    {
        $path = 'data/caches/config/';
        $fileName = $path . $fileName . '.config.php';
        // 判断目录是否存在
        if (!file_exists($path)) {
            mkdir($path, '0777', true);
        }
        file_put_contents($fileName, $data);
    }

    /**
     * 微信分享配置
     */
    public function getWxConfig()
    {
        $result = [
            'appId' => 'wxf79d46c9ce2d1c12',
            'secret' => '329f7fec33e185d8283a8a16ba663192',
            'timestamp' => time(),
            'nonceStr' => '724WUHU',
            'url' => CURRENT_URL
        ];
        // 查询是否有缓存
        $cacheFile = CACHE_PATH . 'config/wx.config.php';
        $create = true;
        // 如果文件存在
        if (file_exists($cacheFile)) {
            // 判断是否过期
            $time = filemtime($cacheFile);
            $time = time() - $time;
            // 没有过期，不重新生成
            if ($time <= 7000) {
                $create = false;
            }
        }
        if ($create) {
            $token = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf79d46c9ce2d1c12&secret=329f7fec33e185d8283a8a16ba663192');
            $token = json_decode($token, true);
            $result['access_token'] = $token['access_token'];
            $ticket = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $result['access_token'] . '&type=jsapi');
            $ticket = json_decode($ticket, true);
            $result['ticket'] = $ticket['ticket'];
            // 写入缓存配置文件
            file_put_contents($cacheFile, json_encode($result));
        } else {
            $content = file_get_contents($cacheFile);
            $result = json_decode($content, true);
            $result['url'] = CURRENT_URL;
        }
        // 签名
        $result['signature'] = sha1('jsapi_ticket=' . $result['ticket'] . '&noncestr=' . $result['nonceStr'] . '&timestamp=' . $result['timestamp'] . '&url=' . $result['url']);
        return $result;
    }

    /*
     * EasyWechat微信第三方库的SDK获取
     *
     * @param String $log_file          日志文件的存放位置
     */
    public static function getEasyWechatApplication($log_file='')
    {
        $options = [
            /**
             * Debug 模式，bool 值：true/false
             *
             * 当值为 false 时，所有的日志都不会记录
             */
            'debug' => true,

            /**
             * 账号基本信息，请从微信公众平台/开放平台获取
             */
            'app_id' => WX_APP_ID,
            'secret' => WX_APP_SECRET,
            'token'  => WX_TOKEN,

            /**
             * 日志配置
             *
             * level: 日志级别, 可选为：
             *         debug/info/notice/warning/error/critical/alert/emergency
             * permission：日志文件权限(可选)，默认为null（若为null值,monolog会取0644）
             * file：日志文件位置(绝对路径!!!)，要求可写权限
             */
            'log' => [
                'level'      => 'error',
                'permission' => 0777,
                'file'       => $log_file ?: WX_LOG_FILE,
            ],

            /**
             * 微信支付
             */
            'payment' => [
                'merchant_id' => WX_MERCHANT_ID,
                'key'         => WX_MERCHANT_KEY,
                'cert_path'   => WX_MERCHANT_CERT_PATH,
                'key_path'    => WX_MERCHANT_KEY_PATH,
            ],
        ];

        return new \EasyWeChat\Foundation\Application($options);
    }
}

?>